package com.Service.impl;

import com.Service.CartService;
import com.mapper.CartMapper;
import com.mapper.ProductMapper;
import com.pojo.Cart;
import com.pojo.CartItemVO;
import com.pojo.Product;
import com.mapper.CartMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public List<CartItemVO> getCartItems(Long userId) {
        List<Cart> cartList = cartMapper.findByUserId(userId);
        List<CartItemVO> voList = new ArrayList<>();
        for (Cart cart : cartList) {
            Product product = productMapper.finById(cart.getProductId());
            CartItemVO vo = new CartItemVO();
            vo.setProduct(product);
            vo.setQuantity(cart.getQuantity());
            voList.add(vo);
        }
        return voList;
    }

    @Override
    public void addToCart(Long userId, Long productId, Long quantity) {
        Cart existing = cartMapper.findByUserIdAndProductId(userId, productId);
        if (existing != null) {
            existing.setQuantity(existing.getQuantity() + quantity);
            cartMapper.update(existing);
        } else {
            Cart cart = new Cart();
            cart.setUserId(userId);
            cart.setProductId(productId);
            cart.setQuantity(quantity);
            cart.setSelected(1L);
            cartMapper.insert(cart);
        }
    }

    @Override
    public void updateCartItem(Long userId, Long productId, Long quantity) {
        Cart cart = cartMapper.findByUserIdAndProductId(userId, productId);
        if (cart != null) {
            cart.setQuantity(quantity);
            cartMapper.update(cart);
        }
    }

    @Override
    public void removeFromCart(Long userId, Long productId) {
        cartMapper.deleteByUserIdAndProductId(userId, productId);
    }
}
